<?php

namespace app\api\model;

use app\api\model\bargain\Active as BargainActiveModel;
use app\api\model\Goods as GoodsModel;
use app\api\model\sharing\Goods as SharingGoodsModel;
use app\api\model\store\Shop as ShopModel;
use app\api\service\sharp\Active as SharpActiveService;
use app\common\library\helper;
use app\common\model\WxappPage as WxappPageModel;
use think\Db;

/**
 * 微信小程序diy页面模型
 * Class WxappPage
 * @package app\api\model
 */
class WxappPage extends WxappPageModel {
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'wxapp_id',
        'create_time',
        'update_time',
    ];

    /**
     * DIY页面详情
     * @param $user
     * @param null $page_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getPageData($user, $page_id = null, $loca) {
        // 页面详情
        $detail = $page_id > 0 ? parent::detail($page_id) : parent::getHomePage();
        // 页面diy元素
        $items = $detail['page_data']['items'];
        // 页面顶部导航
        isset($detail['page_data']['page']) && $items['page'] = $detail['page_data']['page'];
        // 获取动态数据
        $model = new self;
        foreach ($items as $key => $item) {
            if ($item['type'] === 'window') {
                $items[$key]['data'] = array_values($item['data']);
            } else if ($item['type'] === 'goods') {
                $items[$key]['data'] = $model->getGoodsList($user, $item, $loca);
            } else if ($item['type'] === 'sharingGoods') {
                $items[$key]['data'] = $model->getSharingGoodsList($user, $item, $loca);
            } else if ($item['type'] === 'bargainGoods') {
                $items[$key]['data'] = $model->getBargainGoodsList($item);
            } else if ($item['type'] === 'sharpGoods') {
                $items[$key]['data'] = $model->getSharpGoodsList($user, $item, $loca);
            } else if ($item['type'] === 'coupon') {
                $items[$key]['data'] = $model->getCouponList($user, $item, $loca);
            } else if ($item['type'] === 'article') {
                $items[$key]['data'] = $model->getArticleList($item);
            } else if ($item['type'] === 'special') {
                $items[$key]['data'] = $model->getSpecialList($item);
            } else if ($item['type'] === 'shop') {
                $items[$key]['data'] = $model->getShopList($item, $loca);
            }
        }

        return ['page' => $items['page'], 'items' => $items];
    }

    public static function getPageStore($user, $lng_lat =[]) {
        $model = new self;
       
                    $list = Db::name('store_shop')->alias('s')
                        ->join('upload_file u', 'u.file_id=s.logo_image_id')
                        ->where('s.status', 1)
                        ->where('s.is_delete', 0)
                        ->field('s.*,u.file_name')
                        ->select()
                        ->toArray();
                    $lat_lng = '';
                    foreach ($list as $key => $value) {
                        $list[$key]['lat_lng']        = $value['latitude'] . ',' . $value['longitude'];
                        if(isset($lng_lat['longitude'])){
                           // 起点坐标
                  $longitude1 =$lng_lat['longitude'];
                  $latitude1 = $lng_lat['latitude'];
                 // 终点坐标
                    $longitude2 = $value['longitude'];
                    $latitude2 = $value['latitude'];

             
                        $distance = $model->getDistance($longitude1, $latitude1, $longitude2, $latitude2, 2);
                        $list[$key]['km'] =$distance;

                        }
             
               

                        $list[$key]['logo_image'] = self::$base_url . 'uploads/' . $value['file_name'];
                    }
                       if(isset($lng_lat['longitude'])){
                    $list=$model->bubbleSort($list);
                  }


        $lat_lng_array   = array_column($list, 'lat_lng');
        $lat_lng         = implode($lat_lng_array, ';');
        $data['store']   = $list;
        $data['lat_lng'] = $lat_lng;

        return $list;
    }

    public static function getPageStoreDetail($id) {
        $data = Db::name('store_shop')->alias('s')
            ->join('upload_file u', 'u.file_id=s.logo_image_id')
            ->where('s.status', 1)
            ->where('s.is_delete', 0)
            ->where('s.shop_id', $id)
            ->field('s.*,u.file_name')
            ->find();
        //店员
        $store_user = Db::name('store_shop_clerk')->alias('cl')
            ->join('upload_file u', 'u.file_id=cl.logo_image_id')
            ->where('cl.shop_id', $id)
            ->where('status', 1)
            ->where('cl.is_delete', 0)
            ->field('cl.*,u.file_name')
            ->select()
            ->toArray();
        if (!empty($store_user)) {
            foreach ($store_user as $key => $value) {
                $store_user[$key]['logo_image_url'] = self::$base_url . 'uploads/' . $value['file_name'];
            }
        }
        $data['store_user'] = $store_user;

        $data['logo_image_url'] = self::$base_url . 'uploads/' . $data['file_name'];

        return $data;
    }

    /**
     * 商品组件：获取商品列表
     * @param $user
     * @param $item
     * @return array
     * @throws \think\exception\DbException
     */
    private function getGoodsList($user, $item, $loca) {
        // 获取商品数据
        $model = new GoodsModel;
        if ($item['params']['source'] === 'choice') {
            // 数据来源：手动
            $goodsIds  = array_column($item['data'], 'goods_id');
            $goodsList = $model->getListByIdsFromApi($goodsIds, $user);
        } else {
            // 数据来源：自动
            $goodsList = $model->getList([
                'status'      => 10,
                'category_id' => $item['params']['auto']['category'],
                'sortType'    => $item['params']['auto']['goodsSort'],
                'listRows'    => $item['params']['auto']['showNum'],
                'province' => $loca['province'],
                'city' => $loca['city'],
            ], $user);
        }
        if ($goodsList->isEmpty()) {
            return [];
        }
        // 格式化商品列表
        $data = [];
        foreach ($goodsList as $goods) {
            $data[] = [
                'goods_id'      => $goods['goods_id'],
                'goods_name'    => $goods['goods_name'],
                'selling_point' => $goods['selling_point'],
                'image'         => $goods['image'][0]['file_path'],
                'goods_image'   => $goods['image'][0]['file_path'],
                'goods_price'   => $goods['sku'][0]['goods_price'],
                'line_price'    => $goods['sku'][0]['line_price'],
                'return_money'  => $goods['return_money'], // 返现金额
                'goods_sales'   => $goods['goods_sales'],
                'cover_image'   => $goods['coverImage']['file_path'],
                'province_id'   => $goods['province_id'],
                'city_id'   => $goods['city_id'],
            ];
        }
        return $data;
    }

    /**
     * 商品组件：获取拼团商品列表
     * @param $user
     * @param $item
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getSharingGoodsList($user, $item, $loca) {
        // 获取商品数据
        $model = new SharingGoodsModel;
        if ($item['params']['source'] === 'choice') {
            // 数据来源：手动
            $goodsIds  = array_column($item['data'], 'goods_id');
            $goodsList = $model->getListByIdsFromApi($goodsIds, $user);
        } else {
            // 数据来源：自动
            $goodsList = $model->getList([
                'status'      => 10,
                'category_id' => $item['params']['auto']['category'],
                'sortType'    => $item['params']['auto']['goodsSort'],
                'listRows'    => $item['params']['auto']['showNum'],
                'province' => $loca['province'],
                'city' => $loca['city'],
            ], $user);
        }
        if ($goodsList->isEmpty()) {
            return [];
        }
        // 格式化商品列表
        $data = [];
        foreach ($goodsList as $goods) {
            $data[] = [
                'goods_id'      => $goods['goods_id'],
                'goods_name'    => $goods['goods_name'],
                'selling_point' => $goods['selling_point'],
                'people'        => $goods['people'],
                'goods_sales'   => $goods['goods_sales'],
                'image'         => $goods['image'][0]['file_path'],
                'goods_image'   => $goods['image'][0]['file_path'],
                'sharing_price' => $goods['sku'][0]['sharing_price'],
                'goods_price'   => $goods['sku'][0]['goods_price'],
                'line_price'    => $goods['sku'][0]['line_price'],
                'return_money'  => $goods['return_money'], // 返现金额
                'cover_image'   => $goods['coverImage']['file_path'],
                'province_id'   => $goods['province_id'],
                'city_id'       => $goods['city_id'],
            ];
        }
        return $data;
    }

    /**
     * 商品组件：获取拼团商品列表
     * @param $item
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getBargainGoodsList($item) {
        // 获取商品数据
        $model = new BargainActiveModel;
        if ($item['params']['source'] === 'choice') {
            // 数据来源：手动
            $activeIds  = helper::getArrayColumn($item['data'], 'active_id');
            $activeList = $model->getListByIds($activeIds);
        } else {
            // 数据来源：自动
            $activeList = $model->getHallList([
                'sortType' => $item['params']['auto']['goodsSort'],
                'listRows' => $item['params']['auto']['showNum'],
            ]);
        }
        if ($activeList->isEmpty()) {
            return [];
        }

        // 格式化商品列表
        $data = [];
        foreach ($activeList as $item) {
            $data[] = [
                'active_id'      => $item['active_id'],
                'goods_name'     => $item['goods']['goods_name'],
                'goods_image'    => $item['goods']['goods_image'],
                'floor_price'    => $item['floor_price'],
                'original_price' => $item['goods']['goods_sku']['goods_price'],
                'peoples'        => $item['peoples'],
                'helps_count'    => $item['helps_count'],
                'helps'          => $item['helps'],
            ];
        }
        return $data;
    }

    /**
     * 秒杀商品组件：获取秒杀活动
     * @param $item
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getSharpGoodsList($user, $item, $loca) {
        // 获取商品数据
        $service = new SharpActiveService;    
        // 获取秒杀活动及商品列表
        return $service->getSharpModular([
          'limit' => $item['params']['showNum'],
          'province' => $loca['province'],
          'city' => $loca['city'],
        ],$user);
    }

    /**
     * 优惠券组件：获取优惠券列表
     * @param $user
     * @param $item
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getCouponList($user, $item, $loca) {
        // 获取优惠券数据
        return (new Coupon)->getList($user, $item['params']['limit'], true, $loca);
    }

    /**
     * 文章组件：获取文章列表
     * @param $item
     * @return array
     * @throws \think\exception\DbException
     */
    private function getArticleList($item) {
        // 获取文章数据
        $model       = new Article;
        $articleList = $model->getList($item['params']['auto']['category'], $item['params']['auto']['showNum']);
        return $articleList->isEmpty() ? [] : $articleList->toArray()['data'];
    }

    /**
     * 头条快报：获取头条列表
     * @param $item
     * @return array
     * @throws \think\exception\DbException
     */
    private function getSpecialList($item) {
        // 获取头条数据
        $model       = new Article;
        $articleList = $model->getList($item['params']['auto']['category'], $item['params']['auto']['showNum']);
        return $articleList->isEmpty() ? [] : $articleList->toArray()['data'];
    }

    /**
     * 线下门店组件：获取门店列表
     * @param $item
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getShopList($item, $loca) {
        // 获取商品数据
        $model = new ShopModel;
        if ($item['params']['source'] === 'choice') {
            // 数据来源：手动
            $shopIds  = array_column($item['data'], 'shop_id');
            $shopList = $model->getListByIds($shopIds);
        } else {
            // 数据来源：自动
            $shopList = $model->getList(null, false, false, $item['params']['auto']['showNum'], $loca);
        }
        if ($shopList->isEmpty()) {
            return [];
        }

        // 格式化商品列表
        $data = [];
        foreach ($shopList as $shop) {
            $data[] = [
                'shop_id'    => $shop['shop_id'],
                'shop_name'  => $shop['shop_name'],
                'logo_image' => $shop['logo']['file_path'],
                'phone'      => $shop['phone'],
                'region'     => $shop['region'],
                'address'    => $shop['address'],
                'latitude'    => $shop['latitude'],
                'longitude'    => $shop['longitude'],
            ];
        }
        return $data;
    }

    private  function getDistance($longitude1, $latitude1, $longitude2, $latitude2, $unit=2, $decimal=2){
 
    $EARTH_RADIUS = 6370.996; // 地球半径系数
    $PI = 3.1415926;
 
    $radLat1 = $latitude1 * $PI / 180.0;
    $radLat2 = $latitude2 * $PI / 180.0;
 
    $radLng1 = $longitude1 * $PI / 180.0;
    $radLng2 = $longitude2 * $PI /180.0;
 
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
 
    $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $distance = $distance * $EARTH_RADIUS * 1000;
 
    if($unit==2){
        $distance = $distance / 1000;
    }
 
    return round($distance, $decimal);
 
}
private  function bubbleSort($arr)
{  
  $len=count($arr);
  //该层循环控制 需要冒泡的轮数
  for($i=1;$i<$len;$i++)
  { //该层循环用来控制每轮 冒出一个数 需要比较的次数
    for($k=0;$k<$len-$i;$k++)
    {
       if($arr[$k]['km']>$arr[$k+1]['km'])
        {
            $tmp=$arr[$k+1];
            $arr[$k+1]=$arr[$k];
            $arr[$k]=$tmp;
        }
    }
  }
  return $arr;
}

}
